package com.wbl.train.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wbl.train.common.context.LoginMemberContext;
import com.wbl.train.common.exception.ApplicationException;
import com.wbl.train.common.member.dto.PassengerDto;
import com.wbl.train.common.member.entity.PassengerEntity;
import com.wbl.train.common.member.vo.PassengerVo;
import com.wbl.train.common.page.PageVo;
import com.wbl.train.common.result.ResultCode;
import com.wbl.train.common.utils.SnowUtil;
import com.wbl.train.member.mapper.PassengerMapper;
import com.wbl.train.member.service.PassengerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 乘车人 服务实现类
 * @author 王博纶
 * @since 2024-01-26
 */
@Slf4j
@Service
public class PassengerServiceImpl extends ServiceImpl<PassengerMapper,PassengerEntity> implements PassengerService{

    @Override
    public boolean insertAndUpdatePassenger(PassengerEntity passenger) {
        // 获取乘车人的memberId
        Long memberId = LoginMemberContext.getId();
        // 通过memberId进行乘车人信息的查询
        LambdaQueryWrapper<PassengerEntity> wrapper = new LambdaQueryWrapper<PassengerEntity>()
                .eq(PassengerEntity::getMemberId, memberId);

        List<PassengerEntity> passengerList = this.list(wrapper);
        // 获取当前的时间 --- 用于创建和修改的时候的时间填充
        DateTime now = DateTime.now();
        // 设置乘车人的修改时间
        passenger.setUpdateTime(now);
        // 判断Id是否为空
        if(ObjectUtil.isNotNull(passenger.getId())){
            PassengerEntity passengerEntity = this.getById(passenger.getId());
            // 当前id对应的无乘车人
            if(ObjectUtil.isNull(passengerEntity)){
                throw new ApplicationException(ResultCode.DATA_EXIST,"当前乘车人不存在");
            }
            // 更新乘车人
            return this.updateById(passenger);
        }

        // 查询出的passengerEntity不为空，不允许新增
        if(CollUtil.isNotEmpty(passengerList)){
            // CollUtil.forEach的lambda表达式写法
            CollUtil.forEach(passengerList, (data,index) -> {
                if(data.getIdCard().equalsIgnoreCase(passenger.getIdCard())){
                    throw new ApplicationException(ResultCode.DATA_NOT_EXIST,"当前乘车人已存在");
                }
            });
        }
        // 超过50名乘客不允许继续新增
        if(passengerList.size() >= 50){
            throw new ApplicationException(ResultCode.PASSENGER_EXCEED_LIMIT,"当前乘客数量超过50人，不允许继续新增");
        }
        // 给新增的乘车人设置Id，创建时间和修改时间
        passenger.setId(SnowUtil.getSnowflakeNextId())
                .setMemberId(memberId)
                .setCreateTime(now);
        // 新增乘车人
        return this.save(passenger);
    }

    @Override
    public PageVo<PassengerEntity> queryPassenger(PassengerDto passengerDto) {
        Long memberId = passengerDto.getMemberId();
        // 获取分页所需要的参数
        int page = passengerDto.getPage();
        int limit = passengerDto.getLimit();

        LambdaQueryWrapper<PassengerEntity> passengerWrapper = new LambdaQueryWrapper<PassengerEntity>()
                .orderByDesc(PassengerEntity::getId);
        // 会员查询
        if(memberId != null ){
            passengerWrapper.in(PassengerEntity::getMemberId,memberId);
        }
        //创建分页对象
        IPage<PassengerEntity> passengerPage = new Page<>(page,limit);
        //调用分页方法
        IPage<PassengerEntity> passengerPageData = page(passengerPage,passengerWrapper);
        // 获取查询出来的数据集合
        List<PassengerEntity> records = passengerPageData.getRecords();
        // 将数据塞到PageVo类中并返回出去
        return new PageVo<PassengerEntity>()
                .setDataList(records)
                .setPageSize(limit).setCurrentPage(page)
                .setTotal((int) passengerPageData.getTotal())
                .setPages((int) passengerPageData.getPages());
    }

    @Override
    public List<PassengerVo> queryAllMinePassenger() {
        LambdaQueryWrapper<PassengerEntity> wrapper = new LambdaQueryWrapper<PassengerEntity>()
                                                    // 从本地线程中获取当前登录的id ，进行会员过滤
                                                    .eq(PassengerEntity::getMemberId, LoginMemberContext.getId())
                                                    .orderByAsc(PassengerEntity::getName);
        List<PassengerEntity> list = this.list(wrapper);
        return BeanUtil.copyToList(list, PassengerVo.class);
    }
}
